Copyright: Copyright © Colin Davies 1996


TExport
  TExport Component

Properties	Methods	Events	Tasks

Unit

Exporter

Description

The TExport component simplifies the process of exporting data to formatted ASCII files. To use, simply drop the component on your form, configure its properties, connect it to a datasource and then fire it's Execute method.

Set the Datasource property to specify which dataset to access. This can be a table, query or stored procedure. Set the ExportType property to choose variable or fixed length format. Set the Filename property to specify the path and filename of the ASCII file that will be created. Set the OverwriteFile property to overwrite an existing ASCII data file with or without user confirmation. You can specify custom separators by setting the FieldSeparator and RecordSeparator properties, choose fields delimiters by altering the FieldDelimiter property and decide whether just strings or all fields are delimited - DelimitStringsOnly.

By setting the FieldNames property to true, the component will generate an initial ASCII record consisting of the dataset's field names. Memo data can be exported by setting the ExportMemos property with the option of replacing in-memo control characters by setting the ReplaceMemoReturns property.

To select which fields will have their data exported, access the dataset's Fields Editor (FE) and Add the required fields. By setting the ExcludeTagValue property and the instantiated field's Tag properties appropriately you can alter the selection of fields at run time.

You can change the field export order at design time by dragging and dropping within the FE or at run time by setting field Tag values appropriately and using an ExportOrder setting of eoByTagOrder.

The format of each instantiated field can be controlled by setting its DisplayFormat property and field length by setting its DisplayWidth property. Calculated fields may also be included in the dataset.

The component also offers two easy means of automatically monitoring the progess of the export process. Firstly, by specifing the OutputLabel property, the component will display a textual progress message in the specified TLabel object. The frequency of update is controlled by setting the Interval property. Secondly, you can specify a TGauge object which will then automatically display progress in 2% increments.

The component features run-time error checking with returned error codes and automatic error dialogs. These dialogs can be switched off by setting the DisplayErrorDialogs property.

Set the NumRecords property to limit the number of records exported (handy for testing) and access the component's version information by reading the Version property.

To allow other Windows programs to run simultaneously with this component's Execute method, set the ProcessMessages property to true.

See also: 	Installation

Registration


TExport properties
Properties

Datasource	Gauge

DelimitStringsOnly	Interval

DisplayErrorDialogs	Name

ExcludeTagValue	NumRecords

ExportMemos	OutputLabel

ExportOrder	OverwriteFile

ExportType	ProcessMessages

FieldDelimiter	RecordSeparator

FieldNames	ReplaceMemoReturns

FieldSeparator	Tag

Filename	Version


Datasource

Example

Applies to

TExport

Declaration

property Datasource: TDatasource;

Description

Set the Datasource property to any accessible Table or Query.  In the Object Inspector you can select from a drop-down list of datasources available on the same form.


DelimitStringsOnly
DelimitStringsOnly Property

Applies to

Texport

Declaration

property DelimitStringsOnly: boolean ;

Description

If set to true (default) then only data fields of datatype ftString will be embraced by any specified field delimiter character.  If false, then all fields will be delimited by the specified field delimiter. This property is ignored if the ExportType property is set to etFixed.


ExportType
ExportType Property

Applies to

TExport

Declaration

property ExportType: TExportType ;

Description

Can be set to either etVariable (default) or etFixed. A setting of etVariable will generate a Variable length ASCII data file, etFixed will generate a Fixed length ASCII data file. FieldSeparator and FieldDelimiter properties will be ignored if ExportType is set to etFixed.


FieldDelimiter
FieldDelimiter Property

Applies to

TExport, TImport

Declaration

property FieldDelimiter: string;

Description

Optionally specify a field delimiter character which will appear at the start and end of exported/imported field values. In the case of exporting, if the DelimitStringsOnly property is true then only values from fields of datatype ftString will be delimited, otherwise all field values will be delimited. This property only applies when exporting/importing variable length ASCII data files. The default is the double-quote (") character. FieldDelimiters must consist of one single ASCII character only.


FieldSeparator
FieldSeparator Property

Applies to

TExport, TImport

Declaration

property FieldSeparator: string;

Description

If the ExportType or ImportType property is set to variable length (etVariable or itVariable respectively) then you must specify field separator character(s) which will appear between each exported field value. The default is ',' (comma).  If the ExportType/ImportType property is set to fixed length then the FieldSeparator property is irrelevant and will be ignored.

Typically, a field separator will be a single ASCII character but this property will accept a string of characters, including control characters (#nnn).

Examples

A simple field separator::

FieldSeparator := ',';

A multi-character field separator:

FieldSeparator := '~/~'

A field separator using control characters:

FieldSeparator := #13#10 	{CR/LF separated}

    or

FieldSeparator := #9 	{Tab separated}


Filename
Filename Property

Example

Applies to

TExport, TImport

Declaration

property FileName : string ;

Description

Must be set to a valid file path and name for the ASCII file to be exported or imported.


Gauge
Gauge Property

Applies to

TExport, Timport

Declaration

(16 bit components)

property Gauge: TGauge;

(32 bit components)

property Gauge: TProgressBar;

Description

Optionally set to a TGauge/TProgressBar component to automatically display export/import progress. In the Object Inspector you can select from a drop-down list of TGauge/TProgressBar components available on the same form. If set then, when the export/import's Execute method is called, progress will be automatically displayed on the specified TGauge/TProgressBar component in 2% increments.

!6-bit components
The Tgauge component referred to is the component supplied by Borland as part of a standard Delphi v1.x installation and should be found in the 'Samples' component palette tab.  If not, then you will also need to install this component if you wish to take advantage of the Gauge property of the components - see Installation.

32-bit components
The TProgressBar component referred to is the component supplied by Borland as part of a standard Delphi v2.x installation and should be found in the 'Win95' component palette tab.  If not, then you will also need to install this component if you wish to take advantage of the Gauge property of the components - see Installation.


Name
Name Property

Applies to

TExport, TImport

Declaration

property Name: string;

Description

Uniquely identifies each instance of TExport or TImport.


NumRecords
NumRecords Property

Applies to

TExport, TImport

Declaration

property NumRecords: longint;

Description

Specify the maximum number of records to be exported/imported, irrespective of the total record count of the connected dataset. Handy for testing when working with large data volumes. Set to 0 (default) to export/import all available records.


OutputLabel
OutputLabel Property

Applies to

TExport, TImport

Declaration

property OutputLabel: TLabel;

Description

Specifies a TLabel component that the TExport component will automatically use display export progress. The output label is updated every Interval records. In the Object Inspector you can select from a drop-down list of labels available on the same form.

Output when Exporting

The format of the label output during exporting is...

Exporting record NNNN of MMMM

finishing with..

Exported MMMM records

where NNNN is the current record number being processed and MMMM is the maximum number of records in the dataset. Please note that, during the export itself, MMMM is dynamic and can reduce in value if any records are being filtered out by the BeforeExport event.

Output when Importing

The format of the label output during importing is:

Records imported: NNNN

finishing with:

Finished: NNN records imported, PPP posted, RRR rejected, FFF filtered

where NNN is number of records processed by the import, PPP is the number of those records successfully imported, RRR is the number of records rejected because of table-level or field-level errors and FFF is the number of records filtered out by the BeforePost event.


OverwriteFile
OverwriteFile Property

Applies to

TExport

Declaration

property OverwriteFile boolean;

Description

Set to true (default) to automatically overwrite an existing ASCII data file with the filename/path as specified in FileName. If set to false a confirmatory dialog will be presented to the user at run time.


TImport
TImport component

Properties	Methods	Events	Tasks

Unit

Importer

Description

The TImport component simplifies the process of importing data from formatted ASCII files. To use, simply drop the component on your form, configure its properties, connect it to a Table and then fire it's Execute method.

Set the Table property to specify which table will be receiving the imported data. Set the ImportType property to choose variable or fixed length format.

Set the Filename property to specify the path and filename of the ASCII file containing the data to be imported. Specify the FieldSeparator, RecordSeparator and FieldDelimiter used by the ASCII data file by setting those properties.

By default, the order of the import table fields should match the order of the ASCII data fields.To do this, invoke the table's Fields Editor (FE) and Add the required fields in the order required. You may change the persistent field order by dragging and dropping within the FE. However, you can effectively change the field order at run time using the ImportOrder property.

For fixed length imports, the width of each field must match the ASCII data file field widths. This is achieved by setting each table field's DisplayWidth property appropriately.

The component also offers two easy means of automatically monitoring the progess of the import process. Firstly, by specifing the OutputLabel property, the component will display a textual progress message in the specified TLabel object. The frequency of update is controlled by setting the Interval property. Secondly, you can specify a TGauge object which will then automatically display progress in 2% increments.

The component features run-time property error checking to ensure that the component settings are valid, with returned error codes and automatic error dialogs. These dialogs can be switched off by setting the DisplayErrorDialogs property.  The component also offers data error checking, with the automatic creation of an error log, if desired.

Set the NumRecords property to limit the number of records exported (handy for testing) and access the component's version information by reading the Version property.

To allow other Windows programs to run simultaneously with this component's Execute method, set the ProcessMessages property to true.

See also: 	Installation

Registration


Methods

Execute


Execute
TImport Execute method

Applies to

TImport

Declaration

procedure Execute (var RunTimeErrorCode: byte;

     	 var Processed: longint ;

     	 var Rejected: longint ;

     	 var Filtered: longint ;

     	 var ErrorLog: string ;

Description

This is the only method available and launches the import process.  Various checks are made before the import starts and any run-time errors will be reported to the user (unless the DisplayErrorDialogs property is set to false) and the import aborted. During the import, each field in the ASCII import file is matched, in order, against the fields specified in the Fields Editor for the import table. Any field-level errors (e.g. datatype mismatches) and any table-level errors (e.g. key violations, required data missing) will be detected and their details automatically recorded in a ''log' text file. Imported records that generate any errors at all will *not* be posted in the import table. A modal dialog will inform the user at the end of the import that errors have occurred and refer them to the LOG file (unless the DisplayErrorDialogs property is set to false). The creation of error log files can be inhibited by setting the CreateErrorLog property to false. See also Custom Import Data Error Handling


TExport Tasks
Common tasks using the TExport component

Using the TExport component editor

Create Variable length exports

Create Fixed length exports

Export only selected fields

Change the order of exported fields

Filter records for export

Export formatted field values

Export calculated field values

Export memo field values


Fixed length ASCII file example

see also

Example of a fixed length ASCII data file

A. Oliver               15/11/66  135False209.671616

L. Jones                01/03/60   22False128.840829

J, Pricehouse           14/10/6310055True  79.844130

I. Kelly                15/10/65    4False430.279014

H. Pringle              21/10/47    1True  97.8879 2

Each field is padded with trailing spaces up to its maximum length so that its start and end character position is consistent across all records. There are no field delimiters or separators. Records are delimited by a unique character  or character pattern (most commonly CR/LF - i.e. each record is on a new line).


See also


DisplayErrorDialogs
DisplayErrorDialogs Property

Applies to

TExport, TImport

Declaration

property DisplayErrorDialogs: boolean;

Description

When the Execute method is invoked, the TExport/Timport component validates its current property settings and will, if it detects any errors, abort the method, returning runtime error codes. By default the propery is true and the component will also automatically display dialogs to the run-time user showing any error's description. If you want to code your own responses to run-time errors, set this property to false to inhibit the appearance of any error dialogs.


ExportMemos
ExportMemos Property

Applies to

TExport

Declaration

property ExportMemos: boolean;

Description

Set to true (the default is false) to allow the TExport component to export from TMemoField fields. Exporting from memo fields is restricted to variable length exports only - they will be ignored for fixed-length exports. You can set whether CR/LFs within the memo text are converted to spaces (ASCII 32) during the export process or not by setting the property ReplaceMemoReturns to true (default).

If you do decide to export memo text with CR/LF characters (for example, as part of an export file destined for mail-merging in a WP package) then, logically, you must ensure that RecordSeparator property is set to non-CR/LF character(s). If you don't then any CR/LF characters within memo values will be interpreted as end of record markers when the ASCII file is imported.


FieldNames
FieldNames Property

Applies to

TExport

Declaration

property FieldNames: boolean;

Description

If the FieldNames property is set to true (the default is false) then the first row in the exported ASCII data file will contain the exported field's names, not their data values (FieldDelimiter and FieldSeparator settings still apply). The second row of the ASCII data file will therefore contain the first data values. The exported field names are actually taken from the DisplayLabel property of the fields, as specified in the export dataset's Fields Editor. If the DisplayLabel property is not set then the underlying column name is used instead.  Note that the TImport component has no FieldNames property and so will try to treat the first row of such an export as data. This will inevitably cause import errors.

Example ASCII data file with FieldNames = true

"Name","Birthdate","Score","Fulltime","Average","ID"

"A. Oliver",15/11/66,135,"False",209.6716,16

"L. Jones",01/03/60,22,"False",128.8408,29

"J, Pricehouse",14/10/63,10055,"True",379.8441,30

"I. Kelly",15/10/65,4,"False",430.279,14

"H. Pringle",21/10/47,1,"True",297.8879,2


Interval
Interval Property

Applies to

TExport, TImport

Declaration

property Interval: integer;

Description

Specify the frequency with which any specified Outputlabel will be updated as to the progress of the export or import.  For example, specifying an Interval of 25 will cause the OutputLabel caption to be updated every 25 exported records. Default is 10.


ProcessMessages

Example

Applies to

TExport, TImport

Declaration

property ProcessMessages: boolean;

Description

Set to true (default) to allow other Windows messages to be processed whilst the TImport component's Execute method or TExport component's Execute method is running.


ProcessMessagesExample
Example

   if Edit1.text = 'Background' then
    Export1.ProcessMessages := true;


RecordSeparator

Applies to

TExport, TImport

Declaration

property RecordSeparator: string;

Description

Leaving this property as null (default) will cause the exported ASCII records to be separated by CR/LF characters (ASCII #13 and #10), which is the commonest format.  However, you may enter alternative character(s) if you wish, although you must be sure that the chosen character(s) will never appear in field data. You may enter non-standard ASCII characters using the # indicator ... for example, enter #12 for 'form feed' record separators


ReplaceMemoReturns

Applies to

TExport

Declaration

property ReplaceMemoReturns: boolean;

Description

When set to true (default), all CR/LF characters in exported memo text will be replaced with a single space (ASCII 32) character. Tab (ASCII 9) and other control characters are exported as they are.  Note that exporting memo text with CR/LFs not replaced and using a record separator of CR/LF is going to cause record truncation on import. This property is ignored if ExportMemos is set to false.


Version

Applies to

TExport, TImport

Declaration

property Version: string;

Description

This read only property holds the current version information for the component.


Exporter
Exporter Unit

The Exporter unit contains the declarations for just the TExport component.


Create Fixed length exports

Explanation

Create a basic fixed-length ASCII data file thus:

-	Drop a TExport component on the form that contains the required datasource

-	Set the Datasource property to the required datasource

-	Set the ExportType property to etFixed

-	Invoke the Fields Editor for the table (or query) connected to the datasource

-	Add all fields required for export then set the DisplayWidth Field property for each field to the required value

-	Set the Filename property to a valid filepath/name

-	Run the Execute method (e.g. from a button click event)

-	Finished!

Please note that the width of each field in the fixed-length export file is determined by the data field's DisplayWidth property value, as set in the table (or query's) Fields Editor.  By default, when you first create a TTable component on a form and connect it to a table, there are no visible fields in its Fields Editor (invoked by double-clicking on the TTable component) and all underlying fields are inherently selected. In this situation, each field's DisplayWidth property will default to 10 for all field datatypes except ftString, which will default to the length of the field as defined in the table.  If you want fixed length field widths other than these defaults then you must Add all of the fields required for export to the Fields Editor and set DisplayWidth property values accordingly.

Be aware that if the field length (DisplayWidth) is shorter than a field's data value, the data value will be truncated in the export file.  The same applies to exported field names (if the FieldNames property has been set to true)


DataSource Example
Example

if Edit1.Text = 'T' then

  Export1.Datasource := Table1

else

  Export1.Datasource := Query1 ;


TagExample
Example

The following code assumes that the OnClick event handlers of more than one button point to the TForm1.Button1Click method. When a button is clicked, the procedure checks to see if the value of the Tag of the clicked button is 42. If so, the caption of that button is changed.

procedure TForm1.Button1Click(Sender: TObject);

begin

  if (Sender as TButton).Tag = 42 then

    (Sender as TButton).Caption := 'A-Ha!';

end;


Tag

Example

Applies to

TExport, TImport components

Declaration

property Tag: longint;

Description

The Tag property is available to store an integer value as part of a component. Although the Tag property has no semantic meaning to Delphi, your application can use the property to store a value for its special needs.

NB:
Special use can be made of the Tag property of instantiated fields to exclude them (see ExcludeTagValue) and to enable exporting/importing of data in various field orders (see ExportOrder and ImportOrder). The instantiated field's Tag values can be edited via the component editors (TExport component editor, TImport component editor)


Selecting fields
Selecting fields for export

Explanation

Which fields are available for export is governed by the current instantiated field settings in the dataset (table, query or stored procedure) connected to the TExport component via its Datasource property. To access the field settings, invoke the dataset's Fields Editor (FE). By default, the first time you open the Fields editor from a TTable, TQuery, or TStoredProc component, the Fields list is empty and all TFields are dynamically created whenever the dataset is accessed. This effectively means that all fields in the underlying dataset would be available for export. To specify a persistent subset of fields to export click on Add and select the fields you require.  The field order displayed in the FE determines the order of the fields in the exported ASCII data records and can be easily altered by dragging and dropping within the FE.

Instantiated fields can be excluded from the export at run time by setting their Tag values to equal the current setting of the ExcludeTagValue property.

The order in which the fields are exported can also be changed at run time by setting their Tag values and then setting the ExportOrder property to eoByTagOrder.


Export Run Time Errors
TExport Run Time Error Codes

Explanation

When the component's Execute method is first called, it checks its current property settings for errors or inconsistencies. In the event of such an error, the method is aborted and the method's returned Error Code parameter will have a value greater than 0. If there are no errors, the export process proceeds and the method's returned Error Code will be 0.

Error code	Error message	Comments
1	Datasource property not set	You must set the Datasource property
2	Dataset not active	The table's (or query's) Active property is set to false
3	SQL does not contain SELECT statement	The connect query's SQL statement does not return a dataset
4	Filename property must be set	The Filename property is mandatory
5	Field Delimiter may only be 1 char	Entered field delimiter is longer than 1 character
6	Field Separator must be specified	You must set this property if ExportType is set to etVariable
7	Field Separator may only be 1 char	Field separator entered is longer than 1 character
8	Export Type must be specified	You must set the ExportType property
9	Interval must be > 0	The Interval property must be set to an integer value greater than zero
10	Filename is invalid	The filepath/name entered in the FileName property is not a valid DOS filename or path
11	Dataset not available!	The datasource to which the TExport component is connected is itself not connected to a TTable, TQuery component


Registration
Registration and Disclaimer

Registration & Copyright

These components represent many, many hours of design, development, testing and cursing.  If you find them useful and that they save you hours of design, development, testing and cursing, then please let your conscience get the better of you and register them.  They're not expensive and registration is easy, particularly via CompuServe.

The benefits of registration are:

o	The registered version of the components will run outside of the Delphi IDE

o	You will automatically receive free updates for six months following registration

o	You will be entitled to free support via email for six months following registration

o	You may incorporate these components into your projects with no royalties required.

Registration via Compuserve

o	GO to the SWREG forum

o	select the 'Register Shareware' option

o	select the appropriate Region for your mailing address

o	enter a registration ID of '12250' for registration of EXIM v1.2 without source code or '15236' for registration of EXIM v1.2 with source code and click <REGISTER>

o	enter your name, postal address, number of copies, disk formats and how you want the software distributed to you

o	click <CONTINUE> and <SEND>

o	your compuserve account will be then automatically debited the equivalent of US$39.95 (no source code) or $49.95 (including source code) with no shipping/handling costs.

o	I am automatically notified by email of your registration and will distribute the software to you via email usually within 7 working days, but always within 21 working days.

Registration via Snail-mail

o	Raise a UK Sterling cheque or banker's draft for £26.00 (no source code) or £32.00 (with source code) or a US$ money order for US$ 39.95 (no source code) or US$ 49.95 (with source code) plus shipping/handling costs (see below) payable to Colin Davies.

o	Copy and paste the 'ORDER FORM' at the bottom of this screen into Notepad, print it and fill it in (or print the text file shipped as ORDERFRM.TXT)

Post both to:

Colin Davies,
c/o 133 Yarnacott,
Shoeburyness
Essex SS3 8AW
United Kingdom

o	Distribution will take place within 21 working days of the funds being cleared.

Shipping/handling costs (snail-mail distribution only)

To a UK address 	:	£3.00 one copy, plus £0.60p per additional copy

Elsewhere 	:	US$ 5.00 one copy, plus US$1.00 per additional copy

Disclaimer

THE CD EXIM TEXPORT COMPONENT & CD EXIM TIMPORT COMPONENT (COLLECTIVELY REFERRED TO AS "SOFTWARE") ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

Colin Davies
Compuserve 101646,721

Snail-mail Order Form

--------------------------------- cut here ------------------------------------

To: 	Colin Davies,
c/o 133 Yarnacott,
Shoeburyness

Essex SS3 8AW
United Kingdom

Product reference :	EXIM (Delphi v1.1 Export/Import Components)

Price per copy	:	£26.00(UK) (no source code)

£32.00(UK) (with source code)

   or US$39.95 (rest of the world) (no source code)

US$49.95 (rest of the world) (with source code)

Shipping/Handling charges:

Via Compuserve	:	none

To a UK address 	:	£3.00 one copy, plus £0.60p per

additional copy

Elsewhere 	:	US$ 5.00 one copy, plus US$1.00 per

additional copy

Please send _____ copies of the above product, including/excluding* source code to:

Name	:________________________________________

Address	:________________________________________

 ________________________________________

 ________________________________________

 ________________________________________

Postal code	 _____________

Country	 ________________________

I enclose a cheque/money order* for £/US$*: ___________ in respect of

the above, which I understand includes shipping and handling.

I have read the disclaimer.

Signed:	______________________________________________

Date:	__/__/____

* please delete as appropriate

--------------------------------- cut here ------------------------------------


Installation16
Installation of 16-bit EXIM Components

Registration	Component Limitations and Restrictions

Component Installation

PLEASE TAKE A BACKUP COPY OF YOUR COMPONENT LIBRARY (usually C:\DELPHI\BIN\COMPLIB.DCL) BEFORE INSTALLING THESE COMPONENTS.

1)	Unzip the file EXIM16.ZIP and copy the following files to a directory on your Delphi component search path (usually C:\DELPHI\LIB):

EXPORTER.DCU
IMPORTER.DCU
EXEDITOR.DFM
IMEDITOR.DFM
EXPORTER.DCR
IMPORTER.DCR
GAUGES.DCU

2)	GAUGES.DCU should already exist in a default Delphi v1.x installation. If it does, you will find it in the 'Samples' component palette tab.  If not, then you will also need to  install this component if you wish to take advantage of the Gauge property of the components.

3)	Launch Delphi v1.x and select Options/Install Components.

4)	If you have already installed previous versions of EXIM, please Remove the existing EXPORTER and IMPORTER components.

5)	Click the Add button, the Browse button, locate the Delphi component search path and select file EXPORTER.DCU.

6)	Locate IMPORTER.DCU in the same way and select it.

7)	Click OK to install the components.  After a short while, you will notice a new component tab named 'CD Utils' containing the import and export components.

Help installation

PLEASE TAKE A BACKUP COPY OF YOUR DELPHI HELP INDEX FILE (usually C:\DELPHI\BIN\DELPHI.HDX) BEFORE INSTALLING THE EXIM HELP FILES

1)	Copy the supplied file EXIM.HLP to the Delphi BIN subdirectory (usually C:\DELPHI\BIN)

2)	Copy the supplied file EXIM.KWF to the Delphi HELP subdirectory (usually C:\DELPHI\HELP)

3)	 Run \DELPHI\HELP\HELPINST, click File|Open and select C:\DELPHI\BIN\DELPHI.HDX.

4)	Click the + icon and select EXIM.KWF.

5)	Select File|Save to write the updated DELPHI.HDX file, then exit.

You should now be able to access TExport and TImport help from within the Delphi IDE. e.g. by pressing F1 while the cursor is in the OverWriteFile property


Create Variable length exports

see also

Explanation

Create a basic variable length export file thus:

-	Drop a TExport component on the form that contains a valid datasource

-	Set the export component's Datasource property to that datasource

-	Set the export component's ExportType property to etVariable (default)

-	Set the Filename property to a valid filepath/name

-	Run the Execute method (e.g. from a button click event)

-	Finished!

Given the TExport component's defaults, this will create a comma-delimited, variable length ASCII file with double-quote field delimiters (on string fields only) and CR/LF record separators.


Export only selected fields

Explanation

Either invoke the Fields Editor of the TTable/TQuery object connected to the TExport Datasource property and Add only those fields that you require or (particularly at run time) you can set the Tag property of fields you want to exclude to a specific value then set the ExcludeTagValue to that value.


Change the order of exported fields

Explanation

You may invoke the Fields Editor of the TTable/TQuery object connected to the TExport Datasource property and, having Added the fields you require for exportation, drag and drop them to their required positions in the Fields Editor dialog. Alternatively you may export in an order determined by the instantiated field's Tag values. This can be achieved by setting the Tag values of the dataset's instantiated fields to the chosen values (via the Fields Editor), then set TExport's ExportOrder property to eoByTagOrder. This can also be done more conveniently using the Instantiated fields grid in the TExport component editor. Please note that if you need to change the export order dynamically at run-time this is easily achieved by using the 'by Tag Order' technique and simply resetting the Tag values appropriately in your code.


Filter records for export

Explanation

The TExport component will use whatever current dataset settings are in force. So, if exporting from tables set an appropriate index on the TTable component connected to the TExport Datasource property and use the TTable SetRange method to filter the dataset. For Queries set the ORDER BY and WHERE clauses in its SQL property as required.

In addition, individual records can be filtered out (excluded) during the export process by writing appropriate code in the BeforeExport event handler.


Export formatted field values

Applies to

TExport

Explanation

The TExport component will recognise each instantiated field's DisplayFormat property settings and format its exported value appropriately (including calculated fields). Please note that not all field datatypes have a DisplayFormat property (e.g.  ftString).  For example, setting a date field's DisplayFormat property to 'dd-mmm-yyyy' (via the Fields Editor) would cause a value of '12/08/96' to be exported as '12 Aug 1996' (depending on your Window's International settings); or setting a number field's DisplayFormat property to '000000' would cause a value of '1234' to be exported as '001234' .


Export calculated field values

Explanation

Simply create calculated fields in the usual way and add them as a persistent field via the Fields Editor, then drag and drop to give the required order. It is then treated just like any other field, including field formatting.


Export memo field values

Explanation

This is achieved by simply setting the TExport component property ExportMemos to true and adding the memo field(s) as a persistent field (via the Fields Editor) for the relevant TTable, TQuery or TStoredProc component. However, memo export is only allowed using variable-length exports. For fixed-length exports any memo fields will be ignored.  Also, you can choose whether CR/LF characters within memo text is replaced with a space (ASCII 32), or not, by setting the ReplaceMemoReturns property appropriately. If you do decide to export memo text with CR/LF characters (for example, as part of an export file destined for mail-merging in a WP package) then, logically, you must ensure that RecordSeparator property is set to non-CR/LF character(s). If you don't then any CR/LF characters within memo values will be interpreted as end of record markers when the ASCII file is imported.


Variable Length Example See Also
Fixed Length ASCII Data Files


Variable Length ASCII file example
Example of a variable length ASCII data file

"A. Oliver",15/11/66,135,"False",209.6716,16

"L. Jones",01/03/60,22,"False",128.8408,29

"J, Pricehouse",14/10/63,10055,"True",379.8441,30

"I. Kelly",15/10/65,4,"False",430.279,14

"H. Pringle",21/10/47,1,"True",297.8879,2

The above is a classic Comma-Separated Variable-length (CSV) file. Each field value has no leading or trailing spaces and is separated from the next by a specific field separator character, in this case the comma (,).  If the field separator character is likely to appear in field values then the fields must be delimited. In this case only the string (text) fields are delimited. Numbers and dates are not. Note that the third record above has a comma as the second character of the first field but, because the field is delimited, this is will be interpreted just as data, not a field separator. The record separator in the above case is CR/LF - i.e. each record on a new line.

By using less common characters as field separators one can simplify the ASCII data file by not having to use field delimiters. For example, using the tilde (~) character as field separator and no delimiters the above file would look like:

A. Oliver~15/11/66~135~False~209.6716~16

L. Jones~01/03/60~22~False~128.8408~29

J~ Pricehouse~14/10/63~10055~True~379.8441~30

I. Kelly~15/10/65~4~False~430.279~14

H. Pringle~21/10/47~1~True~297.8879~2


Fixed Length Example See Also
Variable length ASCII Data Files


AfterExport event

Example

Applies to

TExport

Declaration

property AfterExport: TAfterExportEvent;

Description

This event has three parameters:

Sender	: Tobject;

DataSource	: TDatasource;

RecordCount	: longint) ;

This event fires just after successful exportation of each record - i.e. only for those records not excluded (filtered) by the BeforeExport event.  Common uses include updating records in related tables, custom progress reporting, audit trails. Code within this event handler may alter the connected datasource's record pointer - e.g. Next, Prior, First, Last - since the component 'bookmarks' it's place in the datasource before the event fires and returns to it once any event handler code has executed. However, the dataset must not change until the TExport execute method has completed - i.e. do not use the Insert, Delete or Append dataset methods within this event handler.


TExport Limitations and Restrictions
EXIM v1.1- Limitations and Restrictions

Restrictions

o	Both the TExport and TImport components have been developed for use with Delphi v1.02 and are not guaranteed to work with other versions of Delphi.

o	Values from field datatypes of ftBlob, ftBytes, ftGraphic, ftUnknown, ftVarBytes cannot be exported. If such fields are included in a persistent dataset (i.e. via the Fields Editor) they will simply be ignored.

o	Fields of datatypes ftMemo, ftBlob, ftBytes, ftGraphic, ftUnknown, ftVarBytes cannot be imported into. If such fields are included in a persistent dataset (i.e. via the Fields Editor) they will simply be ignored.

o	The maximum import ASCII file record length is 2048 characters, including any delimiters and separators. For exporting, the ASCII record length is effectively unlimited.

o	Unregistered versions of the components will only run within the Delphi v1 IDE.


TExport events

BeforeExport

AfterExport


BeforeExport event

Example

Applies to

TExport

Declaration

property BeforeExport: TBeforeExportEvent ;

Description

This event has four parameters:

Sender	: Tobject;

DataSource	: TDatasource;

RecordCount	: longint;

       var 	CanExport	: boolean)

The event is fired just before each record is about to be exported to the ASCII file. Any code in the associated event handler that sets the variable parameter CanExport to false will inhibit the exportation of that record (see Example).

Code within this event handler may alter the connected datasource's record pointer - e.g. Next, Prior, First, Last - since the component 'bookmarks' it's place in the datasource before the event fires and returns to it once any event handler code has executed. However, the dataset must not change until the TExport execute method has completed - i.e. do not use the Insert, Delete or Append dataset methods within this event handler.


BeforeExport Example
BeforeExport event example

The following example would inhibit the export of all records where the field Age had a data value of greater that 45...

procedure Tform1.Export1BeforeExport(Sender	  : Tobject;

  DataSource  : TDatasource;

  RecordCount : longint;

                              var 	  CanExport	  : boolean) ;

begin

  if DataSource.DataSet.FieldByName('Age').AsInteger > 45 then

      CanExport := false

    else

      CanExport := true;

end;


AfterExportExample
Example AfterExport event handler

In this example, as each successfully exported record is processed, an 'audit' table is updated.

procedure TForm1.Export1AfterExport (Sender	  : Tobject;

                                     DataSource : TDatasource;

                                     RecordCount: longint) ;

begin

  with AuditTable do begin

  append;

  FieldByName('ID').AsString := Datasource.dataset.FieldByName('ID').AsString;

  FieldByName('AuditDate').AsDateTime := Date;

  FieldByName('Message').AsString := 'Exported successfully';

  post ;

  end;

end;


TExportType

Unit

Exporter

Declaration

TExportType = (etFixed, etVariable)

Description

The TExportType is the set of values of the ExportType property of a TExport component


TImport overview

Applies to

TImport

General

o	Use the Fields Editor properties to control field sequence and width

o	Component editor available for easy setting of properties

o	Events available for custom user processing before and after each 	record is exported

Properties

CreateErrorLog 	- switch on/off automatic creation of error log file

DisplayErrorDialogs 	- switch on/off run-time error dialogs

FieldDelimiter 	- specify character that delimits fields in variable length format

FieldSeparator 	- specify character that separates fields in variable length format

Gauge 	- connect to a gauge to automatically show progress graphically

ImportOrder	- import either by field name, field order or Tag value

ImportType 	- import data in variable or fixed length format

Interval 	- frequency of OutputLabel update

Name 	- unique TImport instance name

NumRecords 	- limit number of records exported to this maximum

OutputLabel 	- connect to a label to automatically show progress textually

ProcessMessages 	- turn on/off background Windows message processing during import

Table 	- connect to table that will receive the imported data

Version 	- returns the TImport version details

Methods

Execute	- launches import process

Events

BeforePost 	- e.g. use to filter imported records

AfterPost 	- e.g. use to update related tables, audit etc..

OnTableError 	- allows custom error processing of table errors (e.g. key violations)

OnFieldError 	- allows custom error processing of field errors (e.g. invalid date)


Filename Example
Example of FileName property

procedure TForm1.Button1Click(Sender: Tobject);

begin

  Export1.Filename := 'J:\USER1\TEMP\TESTFILE.DAT';

end;


ExcludeTagValue
ExcludeTagValue Property

Applies to

TExport

Declaration

property ExcludeTagValue: string ;

Description

Although this property is a string it expects numbers to be entered (this will be enforced in the TExport component editor). Multiple values can be entered separated by semicolons.

Any fields in the instantiated dataset connected to the TExport component that have a Tag value equal to any of the excluded values will not be exported. By changing this property plus the Tag values of selected instantiated fields at run time, various sets of fields can be exported dynamically.

The default ExcludeTagValue value is ''. Thus, leaving the settings at default will allow all dataset fields to be exported (assuming their datatypes are export compatible - see TExport Limitations & Restrictions).

NB: This property replaces the EXIM v1.1 MatchTagValue property which was rendered incompatible by the introduction of the new ExportOrder property.

Example

Export1.ExcludeTagValue := '1';

Export2.ExcludeTagValue := '1;2;3;4;-1;999';


BeforePost
BeforePost Event

Example

Applies to

TImport

Declaration

event BeforePost: TBeforePostEvent;

Description

This event is fired just before each imported record is posted to the database. Any code in the associated event handler that sets the variable parameter CanImport to false will prevent the record from being posted.

Code within this event handler may alter the connected table's record pointer - e.g. Next, Prior, First, Last - since the component 'bookmarks' it's place in the datasource before the event fires and returns to it once any event handler code has executed. However, the dataset must not change until the TImport Execute method has completed - i.e. do not use the Insert, Delete or Append table methods within this event handler.


TBeforePostEvent type

Unit

Importer

Declaration

TBeforePostEvent = procedure(	Sender: TObject;

Table: TTable;

      RecordCount: longint;

  var	CanImport: boolean) of object ;

Description

The TBeforePostEvent points to a method that notifies a TImport component instance that the current record in the connected ASCII file is about to be posted to the connected table. If the variable parameter CanImport is returned from the method as false then the record posting will be cancelled.


TBeforeExportEvent Type

Unit

Exporter

Declaration

TBeforeExportEvent = procedure(Sender: Tobject; DataSource: TDatasource;

 RecordCount: longint; var CanExport: boolean) of object ;

Description

The TBeforeExportEvent points to a method that notifies a TExport component instance that the current record in the connected data set is about to be exported. if the variable parameter CanExport is returned as false then the record will skipped and not exported.


Importer unit

The Importer unit contains the declarations for just the TImport component.


BeforePost example

To inhibit posting of all records where an Amount field in a connected table is between $1.00 and $100.00 the following code would be entered for this event:

procedure Tform1.Import1BeforePost(Sender	: Tobject;

 Table 	: TTable;

 RecordCount: longint;

                               var CanImport	: boolean) ;

begin

  if (Table.FieldByName('Amount').AsFloat >= 1.00) and

     (Table.FieldByName('Amount').AsFloat <= 100.00) then

      CanImport := false

    else

      CanImport := true;

end;


TImport run-time errors

Explanation

When the TImport component's Execute method is first called, it checks its current property settings for errors or inconsistencies. In the event of such an error, the method is aborted and the method's returned Error Code parameter will have a value greater than 0. If there are no errors, the import process proceeds and the method's returned Error Code will be 0.

Error code	Error message	Comments
1	Table property not set	You must set the Table property
2	Dataset not active	The table's Active property is set to false
3	Filename property must be set	The Filename property is mandatory
4	Interval must be > 0	The Interval property must be set a non-zero integer value
5	Field Separator must be specified	You must set this property if ImportType is set to etVariable
6	Import Type must be specified	You must set the ImportType property
7	Field Delimiter may only be 1 char	Entered FieldDelimiter is > 1 char in length
8	Field Separator character may only be 1 char	FieldSeparator entered is > 1 char in length
9	Import Filename is invalid	The filepath/name entered in the FileName property is not a valid DOS filename or path


Contents
     EXIM ASCII Export/Import VCL Components v1.2

Welcome to the EXIM ASCII TExport/TImport VCL components -  simple to use, yet their comprehensive features will cater for your every ASCII export/import requirement with minimal coding. Royalty-free.

Overview
16-bit / 32-bit Installation
Quick Start
Registration

version 1.1.006


Create fixed length imports

Explanation

Create a basic fixed length ASCII import thus:

-	Drop a TImport component on the form that contains the receiving TTable component

-	Set the import component's Table property to the required table

-	Set the ImportType property to itFixed

-	Invoke the Fields Editor and Add the fields to be imported with the same datatype and in the same order as the ASCII import file record structure

-	Set each field's DisplayWidth property to match the ASCII import file structure

-	Set the Filename property to a valid filepath/name

-	Run the Execute method (e.g. from a button click event)

-	Finished!

NB: To import fixed length ASCII files successfully you must not only ensure that the data types of the import table's fields (as Add'ed to it's Field Editor) are compatible with each corresponding ASCII field, and that they are in the same order, but also that the DisplayWidth property values of the Import table fields exactly matches the ASCII file specification, otherwise the values will be inappropriately parsed and possibly truncated on import.


TExport Execute method

Applies to

TExport

Declaration

procedure Execute (var RunTimeErrorCode: byte;

     	 var Processed: longint ;

     	 var Filtered: longint) ;

Description

This is the only method available and launches the export process.  Various checks are made before the export starts and any run-time errors will be reported to the user (unless the DisplayErrorDialogs property is set to false) and the exort aborted. Three variable parameters are always returned:

o	RunTimeErrorCode will return as 0 if there are no errors or as a value in the range 1 - 11 if there are.

o	Processed will return the total number of records processed for export

o	Filtered will return the number of processed records excluded from the export by any user code programmed in the BeforeExport event handler.

Fields will be exported in the sequence specified in the export dataset's Fields Editor (dbl-click on TTable or TQuery object). If the Fields Editor has not been invoked, then the sequence will be the underlying table field definition order. Exported field values will be formatted according to any settings of that field's DisplayFormat properties as accessed via the Fields Editor.  Note that not all field types have this property.


ImportType property

Applies to

TImport

Declaration

property ImportType: TImportType;

Description

Can be set to either itVariable (default) or itFixed. A setting of itVariable will import a Variable length ASCII file, whereas (maybe not too surprisingly) itFixed will import a Fixed length ASCII file.


TExport overview

Applies to

TExport

General

o	Export from tables, queries and stored procedures

o	Export of calculated fields also supported

o	Use the Delphi Fields Editor to control field sequence, width and format of field values

o	Component editor available for easy setting of properties

o	Events available for custom user processing before and after each 	record is exported

Properties

Datasource 	- can be connected to a table, query or stored procedure

DelimitStringsOnly	- choose whether non-string fields are field delimited or not

DisplayErrorDialogs 	- turn on/off run-time error dialogs

ExportMemos 	- choose whether memo data is exported or not

ExportOrder	- choose to export fields in order or by order of their Tag value

ExportType 	- export data in variable or fixed length format

FieldDelimiter 	- specify character that delimits fields in variable length format

FieldNames 	- export field names as first record of export ASCII file

FieldSeparator 	- specify character that separates fields in variable length format

Filename 	- set export ASCII file path/name to any connected drive

Gauge 	- connect to a gauge to automatically show progress graphically

Interval 	- frequency of OutputLabel update

MatchTagValue	- export only those fields whose Tag property matches this value

NumRecords 	- limit number of records exported to this maximum

Name 	- unique TExport instance name

OutputLabel 	- connect to a label to automatically show progress textually

OverwriteFile 	- turn on/off confirmation run-time of attempt to overwrite existing export file

ProcessMessages 	- choose whether background Windows message processing is on or off during export

RecordSeparator 	- specify character(s) that separates records in either format

ReplaceMemoReturns	- choose whether to automatically replace in-memo CR/LFs with spaces

Version 	- returns the current TExport version details

Methods

Execute	- launches export - returns run-time error codes

Events

AfterExport 	- enter your own code, for example - to update related tables, audit, etc..

BeforeExport 	- enter your own code, for example - to filter/reject records for export


Quick Start

Applies to

TExport, TImport

Description

a)	Create a new project

b)	To the default form, add two Table components, a Datasource, two Buttons, an Export, an Import, Gauge (16-bit) or Progress Bar (32-bit) and a Label

c)	Set Table1.DatabaseName = a database/alias of your choice

d)	Set Table1.TableName = a table containing some data

e)	Set Datasource1.DataSet = Table1

f)	Set Export1.Datasource = Datasource1

g)	Set Export1.Filename = C:\TEMP\TEST.DAT or any other valid filepath/name

h)	Set Export1.Gauge = Gauge1 (16-bit) or ProgressBar1 (32-bit)

i)	Set Export1.OutputLabel = Label1

j)	Set Button1.caption to 'EXPORT'

k)	Create a OnClick handler for Button1 and enter the following code:

var

  b:byte;

  p,r:longint;

begin

  Label1.caption := '';

  Gauge1.progress := 0 ;

  Export1.execute(b,p,r);

end;

l)	Use Database Desktop to make a copy the chosen table (Utilities/Copy) to a different name and then empty it (Utilities/Empty)

m)	Set Table2.DatabaseName = the same as step c)

n)	Set Table2.Tablename = the copy of the table made in step l)

o)	Set Table2.Active = true;

p)	Set Table1.Active = true

q)	Set Import1.Filename = C:\TEMP\TEST.DAT (or same as in step g)

r)	Set Import1.Gauge = Gauge1 (16-bit) or ProgressBar1 (32-bit)

s)	Set Import1.OutputLabel = Label1

t)	Set Import1.Table = Table2

u)	Set Button2.caption to 'IMPORT'

v)	Create a OnClick handler for Button2 with the following code:

var

  b: byte;

  p,r,f: longint;

  e: string;

begin

  Label1.caption := '';

  Gauge1.progress := 0 ;

  Import1.execute(b,p,r,f,e);

end;

w)	Run the project

x)	Click on <Export> button and, providing your chosen export table has data in it, export progress should be displayed on both the gauge and the label.

y)	Check that the output file specified in step g) has been created.

z)	Click on <import> button and import progress should be displayed on both the gauge and the label.

aa)	Use Database Desktop to check that the copy of the table created in step l) has correctly imported the data.


Table Property

Applies to

TImport

Declaration

property Table: TTable;

Description

Specify the TTable component to receive the imported data. In the Object Inspector, you may choose from a drop down list of TTable components on the same form.


TExport/TImport runtime error codes
Runtime error codes

TExport codes
TImport codes


Create Error Log
Create Error Log Property

Applies to

TImport

Declaration

property CreateErrorLog: boolean;

Description

If CreateErrorLog is set to true (default) then, in the event of any table or field level data errors generated during the import execute method, an error log text file is automatically created . If set to false, no error log is created.


Import Error log

Description

In the event of data errors during the import process, and assuming the the CreateErrorLog property is set to true, an ASCII error log file will be created in the same directory as the ASCII import file. The error log filename will be constructed as the name of the calling TImport instance with an extension of .LOG (e.g EXPORT1.LOG). The log is formatted as a traditional 'comma-separated' variable length ASCII file: i.e. double quotes (") used to delimit string fields only, field values separated by commas (,).  The fields in the error log ASCII file are:

Field No	Field Name	Description
1	Import ASCII file line number	The physical line number of the record in the ASCII file, as seen with a text editor, for example
2	Database name	The name of the database, or alias, that owns the import table
3	Table name	Then name of the table into which the unsuccessful post was attempted.
4	Field Name	Then name of the field into which the unsuccessful post was attempted. Note that this field will have a value in the case of a field level data error (e.g. invalid date) but will be blank in the case of a table-level error (e.g. key violation)
5	Error Message	The full text of the generated error message


TImportType Type

Declaration

TImportType = (itFixed, itVariable)


AfterPost Event

Applies to

TImport

Declaration

property AfterExport: TAfterPostEvent;

Description

This event has three parameters:

Sender	: Tobject;

Table	: TTable;

RecordCount	: longint ;

This event fires just after successful posting of each record into the import table - i.e. only for those records not excluded (filtered) by the BeforePost event.  Common uses include updating records in related tables, custom progress reporting, audit trails, etc. Code within this event handler may alter the connected datasource's record pointer - e.g. Next, Prior, First, Last - since the component 'bookmarks' it's place in the datasource before the event fires and returns to it once any event handler code has executed. However, the dataset must not change until the TImport Execute method has completed - i.e. do not use the Insert, Delete or Append dataset methods within this event handler.


TAfterPostEvent type

Unit

Importer

Declaration

TAfterPostEvent = procedure (	Sender: TObject;

Table: TTable;

RecordCount: longint) of object

Description

The TAfterPostEvent points to a method that notifies a TImport component instance that the current record in the connected ASCII file has been successfully posted to the connected table.


OnTableError event

Example

Applies to

TImport

Declaration

event OnTableError: TOnTableErrorEvent;

Description

This event fires each time a table-level error (e.g. Key violation, Required data missing) is detected during the execute method.


TOnTableErrorEvent type

Unit

Importer

Declaration

TOnTableErrorEvent = procedure (	Sender : TObject;

Table	 : TTable;

ErrMsg : string) of object

Description

The TOnTableErrorEvent points to a method that notifies a TImport component instance that the current record in the connected ASCII file has been unsuccessfully posted to the connected table due to a table level error (e.g. key violation, required data missing).

The Table parameter is the import table and ErrMsg is the text of the error message generated by the exception.


OnFieldError event

Applies to

TImport

Declaration

event OnFieldError: TOnFieldErrorEvent;

Description

This event fires each time a field-level error (e.g.invalid date format, not a valid integer) is detected during the execute method.


TOnFieldErrorEvent type

Example

Unit

Importer

Declaration

TOnFieldErrorEvent = procedure (	Sender : TObject;

Table	 : TTable;

Field	 : TField;

ErrMsg : string) of object

Description

The TOnFieldErrorEvent points to a method that notifies a TImport component instance that the current field of the current record in the connected ASCII file has been unsuccessfully converted and/or posted to the connected table (e.g. invalid date, out of range). The Table parameter is the import table - Field is the offending field on that table and ErrMsg is the text of the error message generated by the exception.


Filter records for import

Applies to

TImport

Explanation

Individual records can be filtered out (excluded) during the import process by writing appropriate code in the BeforePost event handler.


TImport properties

CreateErrorLog	Interval

DisplayErrorDialogs	NumRecords

FieldDelimiter	OutputLabel

FieldSeparator	ProcessMessages

FileName	RecordSeparator

Gauge	Table

ImportOrder	Tag

ImportType	Version


TImport methods

Execute


32-bit Installation

Registration	Component Limitations and Restrictions

Component Installation

PLEASE TAKE A BACKUP COPY OF YOUR COMPONENT LIBRARY (usually \DELPHI2\BIN\CMPLIB32.DCL) BEFORE INSTALLING THESE COMPONENTS.

1)	Unzip the file EXIM32.ZIP and copy the following files to a directory on your Delphi component search path (usually \DELPHI2\LIB):

EXPORTER.DCU
EXEDITOR.DFM
IMEDITOR.DFM
IMPORTER.DCU
EXPORTER.DCR
IMPORTER.DCR
GAUGES.DCU

2)	Launch Delphi v2.x and select Component/Install...

4)	If you have already installed previous versions of EXIM, please Remove the existing EXPORTER and IMPORTER components.

5)	Click the Add button, the Browse button, locate the Delphi component search path and select file EXPORTER.DCU.

6)	Locate IMPORTER.DCU in the same way and select it.

7)	Click OK to install the components. The components are installed onto the Data Access component tab.

Help installation

PLEASE TAKE A BACKUP COPY OF YOUR DELPHI HELP INDEX FILE (usually \DELPHI2\BIN\DELPHI.HDX) BEFORE INSTALLING THE EXIM HELP FILES

1)	Copy the supplied files EXIM.HLP, EXIM.KWF to the Delphi HELP subdirectory (usually \DELPHI2\HELP)

2)	 Run \DELPHI2\HELP\TOOLS\HELPINST.EXE, click File|Open and select \DELPHI2\BIN\DELPHI.HDX.

3)	Click the + icon and select EXIM.KWF.

4)	Select File|Save to write the updated DELPHI.HDX file, then exit.

You should now be able to access TExport and TImport help from within the Delphi IDE. e.g. by pressing F1 while the cursor is in the OverWriteFile property (you may have to unload & load Delphi first)


TImport events

BeforePost	OnTableError

AfterPost	OnFieldError


TImport Tasks

Using the TImport component editor

Import Variable length ASCII files

Create Fixed length imports

Filter records for import

Import formatted field values


Import formatted field values

Applies to

TImport

Explanation

When importing data from ASCII files, you must be aware of Delphi's limitations in terms of field data conversions. For example, attempting to import a field value of '3 May 1996' into a ftDateTime field will generate a field-level error. Similarly, importing a field value of '$456.710' into a ftCurrency field will also generate an error.  In such cases, you will have to import the values into string fields then apply your own code, after the import has finished, to convert them.  Generally speaking, it is bad practice to import data directly into live data files just in case their is any corruption (e.g disk media problems). Much better to import the data into a 'buffer' table first, then validate, post (if OK) and clear the buffer table ready for next time. If you adopt this general ploy, then you will also be in a good position to deal with incorrect field formats.


Overview

TExport

TImport


Import Variable Length ASCII files

Explanation

To import a basic variable length export file you must do the following

-	Drop a TTable component on a form and connect to the table that will receive the imported data

-	Drop a TImport component on the form

-	Set the import component's Table property to the TTable component described above

-	Set the import component's ImportType property to itVariable (default)

-	Set the Filename property to the filepath/name of the required ASCII data file

-	Invoke the Table's Fields Editor (dbl-click) and Add the fields that match the chosen ASCII data file record structure. They must be in the same sequence as the fields in the ASCII data file. If you add them in the wrong order you can drag and drop them to the required position.

-	Run the Execute method (e.g. from a button click event)

-	Finished!

Given the TExport component's defaults, this will create a comma-separated, variable length ASCII file with double-quote field delimiters (on string fields only) and CR/LF record separators.


Custom Import Data Error Handling

Applies to

TImport

Description

To implement your own error handling procedures for imports, do the following::

-	Turn off automatic error dialogs by setting the import component's 	DisplayErrorDialogs to false

-	Turn off error log creation by setting the import component's CreateErrorLog property to false

-	Write code for both the OnTableError and OnFieldError event handlers


TAfterExportEvent type

Unit

Exporter

Declaration

TAfterExportEvent = procedure (Sender	: Tobject;

                               DataSource : TDatasource;

                               RecordCount: longint) of object

Description

The TAfterExportEvent type points to a method that notifies a TExport component instance that the current record in the connected datasource has been sucessfully exported.


OnTableError event example

This example will copy the offending import record into an 'ErrorTable' with the same structure as the import table.

procedure Tform1.Import1OnTableError ( Sender	: TObject;
    Table	: TTable;
    ErrMsg	: string) ;

var

  i: Integer;

begin

  for i := 0 to Table.FieldCount - 1 do

    if (not Table.Fields[i].IsNull) then

      ErrorTable.FieldByName(Table.Fields[i].FieldName).Assign(Table.Fields[i]);

end;


OnFieldError event example

This example will copy the offending field details into a custom LOG table.

procedure Tform1.Import1OnFieldError ( Sender	: TObject;

    Table	: TTable;
    Field	: TField;
    ErrMsg	: string) ;

begin

  with LogTable do

  begin

  append;

  FieldByName('FieldName').AsString := Field.Name;

  FieldByName('LogDate').AsDateTime := Date;

  FieldByName('ErrorMessage').AsString := ErrMsg;

  end;

end;


TExportOrderType

Unit

Exporter

Declaration

TexportOrderType = (eoByFieldOrder, eoByTagOrder)

Description

The TExportOrderType is the set of values of the ExportOrder property of a TExport component


ExportOrder

Applies to

TExport

Declaration

property ExportOrder: TExportOrderType;

Description

This property controls the sequence in which the data from the fields in the dataset (see datasource) is exported.

Setting this property to eoByFieldOrder will cause the data to be exported in the instantiated field sequence (i.e. the field sequence as observed in the dataset's Fields Editor). If no fields have been instantiated then the data will be exported in the field sequence as defined in the underlying table/query.

Setting this property to eoByTagOrder will cause the data to be exported in order of the current Tag values of the instantiated fields. Using a combination of eoByTagOrder plus the ExcludeTagValue property enables the developer to control export field selection and sequencing at run time. If this property has been set to eoByTagOrder and no fields have been instantiated then the property setting will be effectively ignored and data will be exported in the field sequence as defined in the underlying table/query.


ImportOrder

Applies to

TImport

Declaration

property ImportOrder: TimportOrderType;

Description

This property controls the sequence in which the data from the field values in the ASCII file are imported.

If this property is set to ioByFieldName, the component will expect the first ASCII row to contain valid import table field names. Subsequent ASCII rows will contain data which will be imported into the appropriate table columns by matching the ASCII field name against the instantiated field name. Data will not be imported where the field names do not match.

If this property is set to ioByFieldOrder, the component will import the ASCII field data directly into the instantiated fields on a positional basis - i.e. first ASCII field into first import table column, second ASCII field into second import table column and so on.

If this property is set to ioByTagValue, then the component will import the ASCII field data into the instantiated fields in the sequence of their current Tag values - i.e. first ASCII field into import table field with the lowest Tag value, second ASCII field into the import table field with the second lowest Tag value and so on.


Using the TExport component editor

The TExport component editor provides a convenient way of setting TExport's properties.  The TExport component editor can be accessed at design time by either...

-	double-clicking on a TExport component or
-	right-clicking on a TExport component and selecting Edit Export Parameters

Most of the options available are self-explanatory except for:

Instantiated Fields grid.

This will display the following information about each instantiated field:

-	Field number (Fld) - i.e. the instantiated field position in the set (as seen in Fields Editor)
-	Tag* - the field's current Tag value (will accept numbers only)
-	Name
-	Type
-	Len* - the current value of the field's DisplayWidth property (will accept numbers only)
-	Format* - the current value of the field's Format property (if it has one)

* can be edited in the grid

ExcludeTagValues.

Although the ExcludeTagValue property is a string type, this field will only accept numbers, semi-colons and minus signs. Multiple values can be entered separated by semi-colons:

e.g. 1;2;3;4;5;6;-1;-2;

If the ExportOrder drop-down list value is set to By Tag Order then the grid will be sorted by Tag order and a Resort Field Grid button will appear. If you alter Tag values you can resort the grid by clicking this button or reselecting and ExportOrder of By Tag Order


Component editor: Filename


Component editor: Datasource?


Component editor: Overwrite?


Using the TImport component editor

The TImport component editor provides a convenient way of setting TImport's properties.  The TImport component editor can be accessed at design time by either...

-	double-clicking on a TImport component or
-	right-clicking on a TImport component and selecting Edit Import Parameters

Most of the options available are self-explanatory except for the Instantiated Fields grid. This will display the following information about each instantiated field:

-	Field number (Fld) - i.e. the instantiated field position in the set (as seen in Fields Editor)
-	Tag* - the field's current Tag value (will accept numbers only)
-	Name
-	Type
-	Len* - the current value of the field's DisplayWidth property (will accept numbers only)

* can be edited in the grid

If the ImportOrder dop-down list value is set to By Tag Order then the grid will be sorted by Tag order and a Re-sort Field Grid button will appear. If you alter Tag values you can resort the grid by clicking this button or reselecting and ImportOrder of By Tag Order


TimportOrderType

Unit

Importer

Declaration

TimportOrderType = (ioByFieldName, ioByFieldOrder, ioByTagValue)

Description

The TimportOrderType is the set of values of the ImportOrder property of a TImport component.